const express = require('express')
const app = express()
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const passport = require('passport')
const port = process.env.PORT || 5000

//映入路由设计
const users = require('./routes/api/users')
const profile = require('./routes/api/profile')
const posts = require('./routes/api/posts')


// db config
const db = require('./config/keys').mongoURL
mongoose.connect(db, { useNewUrlParser: true })
    .then(() => console.log("MongoDB Connected"))
    .catch((err) => console.log(err))

// 允许跨域请求
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");         //允许的来源
    res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");    //请求的头部
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");  //允许请求的方法
    next();
})


// app.get('/', (req, res) => {
//     res.send('hello world')
// })

// passport初始化
app.use(passport.initialize());
// app.use(passport.session());
require('./config/passport')(passport)


// 使用body-parser 中间件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 使用router
app.use('/api/users', users)
app.use('/api/profile', profile)
app.use('/api/posts', posts)

app.listen(port, () => {
    console.log(`server running on port ${port}`);

})